<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\FormException;
use App\Http\Controllers\LayuiController;
use App\Models\Banner;
use App\Models\Goods;
use App\Services\UploadService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ActiveBannerController extends Controller
{
    /**
     * 列表页视图
     * @name index
     * @param \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/23 10:23
     */
    public function index(){

        $data = Banner::where('origin',Banner::ActiveBanner)
            ->select('id','remark')
            ->get()
            ->mapWithKeys(function($item){
                return [$item->id => $item->remark];
            });
        return view('Admin.activeBanner.index', ['data' => $data]);
    }

    /**
     * 列表页表格数据方法
     * @name table
     * @param array
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 9:43
     */
    public function table(Request $request){

        $data = Banner::orderBy('id','asc')
            ->where('origin',Banner::ActiveBanner)
            ->get();

        return LayuiController::tableJson($data,0,$data->count());
    }

    /**
     * 状态修改方法
     * @name status
     * @param \Illuminate\Http\JsonResponse
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 9:43
     */
    public function status(Request $request){

        DB::beginTransaction();
        try{
            $id = $request->input('id');
            $model = Banner::findOrFail($id);
            $model->status = $model->status == Banner::statusTrue ? Banner::statusFail : Banner::statusTrue;
            $model->save();

        }catch (\Exception $exception){

            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '设置失败' );

        }

        DB::commit();
        return $this->getResponseSuccess('设置成功');
    }

    /**
     * 编辑展示页面
     * @name edit
     * @param \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 9:43
     */
    public function edit(Request $request,$id){
        $data = Banner::findOrFail($id);
        return view('Admin.activeBanner.edit',['data' => $data]);
    }

    /**
     * 编辑AJAX保存操作
     * @name update
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 10:11
     */
    public function update(Request $request,$id){
        $payload  = $request->only(['remark','status','jump_url','goods_id']);
        $payload['status'] = $request->input('status',Banner::statusFail);
        Validator::make($payload, [
            'remark'      => 'required',
            'status'      => 'required|in:1,2',
            'goods_id'    => 'required_if:jump_url,false',
        ],[
            'remark.required'   => '请输入活动名称',
            'status.required'   => '请选择活动状态',
            'status.in'         => '请选择活动状态',
            'goods_id.required_if' => '请选择商品详情',
        ])->validate();

        DB::beginTransaction();

        try{
            $model = Banner::findOrFail($id);

            if($request->hasFile('photo')){
                $UploadService = new UploadService($request,'activeBanner','photo','oss');
                $uploadresult = $UploadService->upload();

                if($uploadresult['status'] == UploadService::FailStatus){
                    throw new \Exception($uploadresult->message ?? '图片上传失败');
                }
                $model->photo = $uploadresult['url'];
            }


            $model->remark = $payload['remark'];
            $model->status = $payload['status'];
            if($payload['jump_url']){
                if($payload['jump_url'] != 'false'){
                    $model->jump_url = $payload['jump_url'];
                }else{
                    $goodsInfo = Goods::findOrFail($payload['goods_id']);
                    $model->jump_url = "/pages/goodsDetail/goodsDetail?goodsId={$goodsInfo->id}&code=&sku={$goodsInfo->sku}";
                }
            }
            $model->save();

        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        DB::commit();
        return $this->getResponse('保存成功');
    }

}
